package org.sardine.beans.support;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.sardine.beans.BeanContainer;
import org.sardine.util.Assert;

public class ElmBeanDefinitionValueResolver {
	
	private static final Logger log = Logger.getLogger(ElmBeanDefinitionValueResolver.class);
	private final BeanContainer beanContainer;
	private final Object beanObject;
	
	public ElmBeanDefinitionValueResolver(BeanContainer beanContainer,Object beanObject){
		this.beanContainer = beanContainer;
		this.beanObject = beanObject;
	}
	
	/**
	 * 
	 * 解析元素定义的value值，该value值的定义类型必须是String、RefType、ListType、SetType或MapType
	 * 
	 * @param elmPropertyValue	元素的value值的定义类型
	 * @return
	 */
	public Object resolveValue(Object elmPropertyValue){
		
		Assert.notNull(elmPropertyValue, "elmPropertyValue不能为空");
		
		if(elmPropertyValue instanceof String){
			log.debug("value属性值的定义类型是String,值为\""+(String)elmPropertyValue+"\"");
			return (String)elmPropertyValue;
			
		}else if(elmPropertyValue instanceof RefType){
			return resolveRefValue((RefType)elmPropertyValue);
			
		}else if(elmPropertyValue instanceof ListType){
			return resolveListValue((List)elmPropertyValue);
			
		}else if(elmPropertyValue instanceof SetType){
			return resolveSetValue((Set)elmPropertyValue);
			
		}else if(elmPropertyValue instanceof MapType){
			return resolveMapValue((Map)elmPropertyValue);
			
		}else{
			throw new IllegalArgumentException("无法处理"+elmPropertyValue.getClass()+"这个类型的fieldValue");
		}
	}
	
	private Object resolveRefValue(RefType refValue){
		
		log.debug("value属性值的定义类型是RefType,id为\""+refValue.getRefId()+"\"");
		
		Object obj = this.beanContainer.getBean(refValue.getRefId());
		return obj;
	}
	
	private List resolveListValue(List listValue){
		
		log.debug("value属性值的定义类型是ListType，大小为："+listValue.size());
		
		List ls = new ArrayList();
		Iterator it = listValue.iterator();
		while(it.hasNext()){
			ls.add(resolveValue(it.next()));
		}
		return ls;
	}
	
	private Set resolveSetValue(Set setValue){
		
		log.debug("value属性值的定义类型是SetType，大小为："+setValue.size());
		
		Set st = new HashSet();
		Iterator it = setValue.iterator();
		while(it.hasNext()){
			st.add(resolveValue(it.next()));
		}
		return st;
	}
	
	private Map resolveMapValue(Map mapValue){
		
		log.debug("value属性值的定义类型是MapType，大小为："+mapValue.size());
		
		Map mp = new HashMap();
		Iterator it = mapValue.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry entry = (Map.Entry)it.next();
			//Object mpKey = resolveValue(elmPropertyName,entry.getKey());
			//Object mpValue = resolveValue(elmPropertyName,entry.getValue());
			Object mpKey = entry.getKey();
			log.debug("开始解析<map key=\""+mpKey.toString()+"\"/>的value属性类型");
			Object mpValue = resolveValue(entry.getValue());
			mp.put(mpKey, mpValue);
		}
		return mp;
	}

}
